<template>
  <div class="app-container">
    <!-- <div class="header-container"> -->
      <!-- <el-button icon="el-icon-arrow-left" @click="goBack" size="small" style="margin-right: 15px;">
        返回
      </el-button> -->
      <!-- <h2>客户配置</h2> -->
    <!-- </div> -->

    <el-tabs v-model="activeTab">
      <el-tab-pane label="客户流转" name="flow">
        <FlowConfig ref="flowConfig" :config-data="configData.flow" />
      </el-tab-pane>

      <el-tab-pane label="客户提醒" name="remind">
        <RemindConfig ref="remindConfig" :config-data="configData.remind" />
      </el-tab-pane>

      <el-tab-pane label="公海流转" name="public">
        <PublicConfig ref="publicConfig" :config-data="configData.public" />
      </el-tab-pane>

      <el-tab-pane label="防骚扰设置" name="antiHarass">
        <AntiHarassConfig ref="antiHarassConfig" :config-data="configData.antiHarass" />
      </el-tab-pane>

      <el-tab-pane label="跟进阶段设置" name="followStage">
        <FollowStageConfig ref="followStageConfig" :config-data="configData.followStage" />
      </el-tab-pane>
    </el-tabs>

    <div class="footer-actions">
      <el-button type="primary" @click="handleSaveAll" :loading="saving" size="medium">确定</el-button>
      <el-button @click="handleReset" size="medium">重置</el-button>
    </div>
  </div>
</template>

<script>
import FlowConfig from './components/FlowConfig.vue'
import RemindConfig from './components/RemindConfig.vue'
import PublicConfig from './components/PublicConfig.vue'
import AntiHarassConfig from './components/AntiHarassConfig.vue'
import FollowStageConfig from './components/FollowStageConfig.vue'

import { addConfig, listConfig } from "@/api/customer/config"


export default {
  name: "CustomerConfig",
  components: {
    FlowConfig, RemindConfig, PublicConfig, AntiHarassConfig, FollowStageConfig
  },
  data() {
    return {
      activeTab: 'flow',
      saving: false,
      configData: {
        flow: {}, remind: {}, public: {}, antiHarass: {}, followStage: {}
      }
    }
  },
  created() {
    this.getConfigs()
  },
  methods: {
    // 获取配置列表
    getConfigs() {
      listConfig().then(response => {
        const dbData = response.rows || []
        console.log('从数据库加载的原始数据:', dbData)

        // 直接转换数据格式并赋值
        this.configData = this.transformToFrontendFormat(dbData)
      })
    },

    // 新增方法：将数据库格式转换为前端组件需要的格式
    transformToFrontendFormat(dbData) {
      const frontendData = {
        flow: { normal: {}, vip: {} },
        remind: { customerDrop: {}, assignRemind: {} },
        public: { normal: {}, vip: {} },
        antiHarass: { followFrequency: {} },
        followStage: { stages: [] }
      }

      // 根据数据库中的 type 和 configKey 映射到对应字段
      dbData.forEach(item => {
        // 客户流转配置 (type=1)
        if (item.type === 1) {
          if (item.configKey === 'crm_first') {
            frontendData.flow.normal.firstFollow = item.value
          } else if (item.configKey === 'crm_next') {
            frontendData.flow.normal.continuousFollow = item.value
          } else if (item.configKey === 'crm_deal') {
            frontendData.flow.normal.orderComplete = item.value
          } else if (item.configKey === 'big_first') {
            frontendData.flow.vip.firstFollow = item.value
          } else if (item.configKey === 'big_next') {
            frontendData.flow.vip.continuousFollow = item.value
          } else if (item.configKey === 'big_deal') {
            frontendData.flow.vip.orderComplete = item.value
          }
        }

        // 客户提醒配置 (type=2)
        else if (item.type === 2) {
          if (item.configKey === 'first') {
            frontendData.remind.customerDrop.firstFollow = item.value
          } else if (item.configKey === 'next') {
            frontendData.remind.customerDrop.continuousFollow = item.value
          } else if (item.configKey === 'deal') {
            frontendData.remind.customerDrop.orderComplete = item.value
          } else if (item.configKey === 'dept') {
            frontendData.remind.assignRemind.department = item.value
          } else if (item.configKey === 'mcn') {
            frontendData.remind.assignRemind.organization = item.value
          }
        }

        // 公海流转配置 (type=3)
        else if (item.type === 3) {
          if (item.configKey === 'crm_dept') {
            frontendData.public.normal.departmentToTalent = item.value
          } else if (item.configKey === 'crm_mcn') {
            frontendData.public.normal.talentToOrganization = item.value
          } else if (item.configKey === 'big_dept') {
            frontendData.public.vip.departmentToTalent = item.value
          } else if (item.configKey === 'big_mcn') {
            frontendData.public.vip.talentToOrganization = item.value
          }
        }

        // 防骚扰配置 (type=4)
        else if (item.type === 4) {
          if (item.configKey === 'phone') {
            frontendData.antiHarass.followFrequency.phone = item.value
          } else if (item.configKey === 'message') {
            frontendData.antiHarass.followFrequency.message = item.value
          } else if (item.configKey === 'sms') {
            frontendData.antiHarass.followFrequency.sms = item.value
          }
        }

        // 跟进阶段配置 (type=5)
        else if (item.type === 5 && item.configKey === 'follow_stages') {
          try {
            frontendData.followStage.stages = JSON.parse(item.value)
          } catch (e) {
            frontendData.followStage.stages = []
          }
        }
      })

      return frontendData
    },

    async handleSaveAll() {
      this.saving = true;
      // try {
      // 收集所有配置数据
      const allConfig = {
        flow: this.$refs.flowConfig?.getFormData() || {},
        remind: this.$refs.remindConfig?.getFormData() || {},
        public: this.$refs.publicConfig?.getFormData() || {},
        antiHarass: this.$refs.antiHarassConfig?.getFormData() || {},
        followStage: this.$refs.followStageConfig?.getFormData() || {}
      };

      // 转换为数据库格式
      const dbData = this.transformToDbFormat(allConfig);
      console.log('这个是我提交的数据了', dbData)

      addConfig(dbData).then(res => {
        this.$modal.msgSuccess("保存成功")
        this.saving = false
        console.log('提交api的结果', res)
      })

    },


    // 将前端数据转换为数据库格式
    transformToDbFormat(configData) {
      const dbRecords = [];

      // 1. 客户流转配置
      if (configData.flow) {
        // 普通客户配置
        dbRecords.push({
          type: 1, // 客户流转
          op: 1,   // 普通客户
          configKey: 'crm_first',
          value: configData.flow.normal?.firstFollow || '24',
          name: '普通客户首跟流转'
        });
        dbRecords.push({
          type: 1,
          op: 1,
          configKey: 'crm_next',
          value: configData.flow.normal?.continuousFollow || '7',
          name: '普通客户连跟流转'
        });
        dbRecords.push({
          type: 1,
          op: 1,
          configKey: 'crm_deal',
          value: configData.flow.normal?.orderComplete || '30',
          name: '普通客户成单流转'
        });

        // 大客户配置
        dbRecords.push({
          type: 1,
          op: 2,   // 大客户
          configKey: 'big_first',
          value: configData.flow.vip?.firstFollow || '48',
          name: '大客户首跟流转'
        });
        dbRecords.push({
          type: 1,
          op: 2,   // 大客户
          configKey: 'big_next',
          value: configData.flow.vip?.firstFollow || '14',
          name: '大客户连跟流转'
        });
        dbRecords.push({
          type: 1,
          op: 2,   // 大客户
          configKey: 'big_deal',
          value: configData.flow.vip?.firstFollow || '60',
          name: '大客户连跟流转'
        });
        // ... 其他大客户配置
      }

      // 2. 客户提醒配置
      if (configData.remind) {
        dbRecords.push({
          type: 2, // 客户提醒
          configKey: 'first',
          value: configData.remind.customerDrop?.firstFollow || '24',
          name: '客户掉库首跟提醒'
        });
        dbRecords.push({
          type: 2, // 客户提醒
          configKey: 'next',
          value: configData.remind.customerDrop?.continuousFollow || '7',
          name: '客户掉库连跟提醒'
        });
        dbRecords.push({
          type: 2, // 客户提醒
          configKey: 'deal',
          value: configData.remind.customerDrop?.orderComplete || '30',
          name: '客户掉库成单提醒'
        });
        dbRecords.push({
          type: 2, // 客户提醒
          configKey: 'dept',
          value: configData.remind.assignRemind?.department || '3',
          name: '客户机构公海分配提醒'
        });
        dbRecords.push({
          type: 2, // 客户提醒
          configKey: 'mcn',
          value: configData.remind.assignRemind?.organization || '5',
          name: '客户达人公海分配提醒'
        });
        // ... 其他提醒配置
      }

      // 3. 公海流转配置
      if (configData.public) {
        dbRecords.push({
          type: 3, // 公海流转
          configKey: 'crm_dept',
          value: configData.public.normal?.departmentToTalent || '7',
          name: '普通客户部门公海流转'
        });
        dbRecords.push({
          type: 3, // 公海流转
          configKey: 'crm_mcn',
          value: configData.public.normal?.talentToOrganization || '15',
          name: '普通客户机构公海流转'
        });
        dbRecords.push({
          type: 3, // 公海流转
          configKey: 'big_dept',
          value: configData.public.vip?.departmentToTalent || '14',
          name: '大客户部门公海流转'
        });
        dbRecords.push({
          type: 3, // 公海流转
          configKey: 'big_mcn',
          value: configData.public.vip?.talentToOrganization || '30',
          name: '大客户部门公海流转'
        });

        // ... 其他公海配置
      }

      // 4. 防骚扰配置
      if (configData.antiHarass) {
        dbRecords.push({
          type: 4, // 防骚扰
          configKey: 'phone',
          value: configData.antiHarass.followFrequency?.phone || '3',
          name: '电话跟进频次'
        });
        dbRecords.push({
          type: 4, // 防骚扰
          configKey: 'message',
          value: configData.antiHarass.followFrequency?.message || '5',
          name: '电话跟进频次'
        });
        dbRecords.push({
          type: 4, // 防骚扰
          configKey: 'sms',
          value: configData.antiHarass.followFrequency?.sms || '2',
          name: '电话跟进频次'
        });
        // ... 其他防骚扰配置
      }

      // 5. 跟进阶段配置（特殊处理）
      if (configData.followStage) {
        dbRecords.push({
          type: 5, // 跟进阶段
          configKey: 'follow_stages',
          value: JSON.stringify(configData.followStage.stages || []),
          name: '跟进阶段列表'
        });
      }

      return dbRecords;
    },


    handleReset() {
      const refMap = {
        flow: 'flowConfig', remind: 'remindConfig', public: 'publicConfig',
        antiHarass: 'antiHarassConfig', followStage: 'followStageConfig'
      }
      const refName = refMap[this.activeTab]
      if (this.$refs[refName]?.handleReset) {
        this.$refs[refName].handleReset()
      }
    },

    // goBack() {
    //   this.$router.go(-1)
    // }
  }
}
</script>

<style scoped>
.header-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  align-items: center;
}

.header-container h2 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.footer-actions {
  margin-top: 10px;
  text-align: center;
  padding: 20px 0;
  border-top: 1px solid #ebeef5;
}
</style>